<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>系统告警 - 御物联</title>
    <!-- Chart.js CDN - 使用国内 CDN (BootCDN) -->
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        :root{--primary:#409EFF;--stage-bg:#EDE3D3;--bg:#F5F7FA;--text:#303133;--subtext:#909399;--card:#FFFFFF;--border:#EBEEF5;--ok:#67C23A;--warn:#E6A23C;--danger:#F56C6C}
        body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;background:var(--stage-bg);color:var(--text)}
        .page{min-height:100vh;max-width:480px;margin:0 auto;background:var(--bg);padding-bottom:calc(72px + env(safe-area-inset-bottom))}
        /* 页头样式与页脚保持一致 */
        .header-box{position:sticky;top:0;z-index:20;background:var(--card);border-bottom:1px solid var(--border);box-shadow:0 -2px 8px rgba(0,0,0,.04);padding:12px;display:flex;justify-content:space-between;align-items:center;margin:0;border-radius:0}
        .header-box > *:first-child{ flex-shrink:0; }
        .project-select-btn{ padding:0 28px 0 14px; height:32px; border-radius:16px; background:var(--card); border:1px solid var(--border); display:inline-flex; align-items:center; gap:0; color:var(--text); box-shadow:0 1px 3px rgba(0,0,0,.03); cursor:pointer; font-size:14px; transition:all 0.2s; white-space:nowrap; width:160px; overflow:hidden; position:relative; flex-shrink:0; }
        .project-select-btn:hover{ background:var(--bg); border-color:var(--primary); color:var(--primary); }
        .project-select-btn::after{ content:'▼'; font-size:10px; position:absolute; right:10px; top:50%; transform:translateY(-50%); flex-shrink:0; z-index:2; background:var(--card); padding:0 2px; }
        .project-select-btn:hover::after{ background:var(--bg); }
        .project-select-btn span{ white-space:nowrap; display:block; overflow:hidden; text-overflow:ellipsis; max-width:calc(100% - 20px); position:relative; z-index:1; }
        .back-btn{padding:0 12px;height:32px;border-radius:16px;background:var(--card);border:1px solid var(--border);display:flex;align-items:center;gap:6px;color:var(--text);box-shadow:0 1px 3px rgba(0,0,0,.03);cursor:pointer;font-size:14px;transition:all 0.2s}
        .back-btn:hover{background:var(--bg);border-color:var(--primary);color:var(--primary)}
        .back-btn::before{content:'←';font-size:16px;line-height:1}
        .toolbar{display:flex;justify-content:flex-end;gap:10px;padding:12px 12px 8px;position:sticky;top:0;background:linear-gradient(180deg, rgba(245,247,250,1) 70%, rgba(245,247,250,0));z-index:10;align-items:center}
        .user{padding:0 10px;height:32px;border-radius:16px;background:var(--card);border:1px solid var(--border);display:flex;align-items:center;gap:8px;color:var(--text);box-shadow:0 1px 3px rgba(0,0,0,.03); margin-left:auto; }
        .user-avatar{width:22px;height:22px;border-radius:50%;background:var(--primary);color:#fff;display:flex;align-items:center;justify-content:center;font-size:12px}
        .select{flex:1;height:44px;border:1px solid var(--border);border-radius:10px;background:var(--card);padding:0 12px;color:var(--text);font-size:14px}
        .filters{display:flex;gap:8px;padding:16px 12px 10px;flex-wrap:wrap;align-items:center}
        .search-input{flex:1;height:36px;border:1px solid var(--border);border-radius:6px;background:var(--card);padding:0 12px;color:var(--text);font-size:14px;min-width:120px}
        .filter-select{height:36px;border:1px solid var(--border);border-radius:6px;background:var(--card);padding:0 12px;color:var(--text);font-size:14px;min-width:100px}
        .btn-primary{height:36px;padding:0 12px;border-radius:6px;border:none;background:var(--primary);color:#fff;font-size:14px;white-space:nowrap}
        .btn-plain{height:36px;padding:0 12px;border-radius:6px;border:1px solid var(--border);background:#fff;color:var(--text);font-size:14px;white-space:nowrap}
        .filter-row{display:flex;gap:8px;padding:0 0 8px;flex-wrap:wrap;align-items:center;width:100%}
        /* 第一行：时间周期 */
        .filter-row:first-of-type .filter-select{flex:1;min-width:120px}
        /* 第二行：告警等级、状态 - 比例1:1 */
        .filter-row:nth-of-type(2) .filter-select{flex:1;min-width:100px}
        .button-row{display:flex;gap:8px;padding:0 0 10px;justify-content:flex-end;align-items:center;width:100%}
        .button-row .btn-primary{min-width:80px;margin-left:auto}
        .button-row .btn-plain{min-width:80px}
        /* Tab样式 */
        .tab-container{margin:0 12px 12px}
        .tab-header{display:flex;background:var(--card);border-radius:12px 12px 0 0;overflow:hidden;border:1px solid var(--border);border-bottom:none}
        .tab-btn{flex:1;padding:12px;background:var(--bg);color:var(--subtext);border:none;font-size:14px;cursor:pointer;transition:all 0.2s}
        .tab-btn.active{background:var(--card);color:var(--primary);font-weight:600}
        .tab-content{display:none;background:var(--card);border:1px solid var(--border);border-radius:0 0 12px 12px;min-height:400px}
        .tab-content.active{display:block}
        
        /* 告警报表样式 */
        .report-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;padding:16px;margin-bottom:16px}
        .stat-card{background:var(--bg);border-radius:8px;padding:16px;text-align:center}
        .stat-value{font-size:24px;font-weight:600;color:var(--primary);margin-bottom:4px}
        .stat-label{font-size:12px;color:var(--subtext)}
        .chart-container{height:300px;padding:16px;position:relative}
        
        /* 等级统计样式 */
        .level-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;padding:0 16px 16px}
        .level-card{background:var(--bg);border-radius:6px;padding:12px;text-align:center;border-left:4px solid var(--primary)}
        .level-card.warning{border-left-color:var(--warn)}
        .level-card.danger{border-left-color:var(--danger)}
        .level-card.info{border-left-color:#909399}
        .level-value{font-size:18px;font-weight:600;margin-bottom:2px}
        .level-label{font-size:11px;color:var(--subtext)}
        .level-value.warning{color:var(--warn)}
        .level-value.danger{color:var(--danger)}
        .level-value.info{color:#909399}
        
        /* 告警详情样式 */
        .list{background:var(--card);border:1px solid var(--border);border-radius:12px;margin:12px;overflow:hidden}
        .row{padding:12px 14px;border-bottom:1px solid var(--border)}
        .row:last-child{border-bottom:none}
        .meta{display:flex;gap:6px;flex-wrap:wrap;color:var(--subtext);font-size:13px;margin-bottom:8px}
        .tag{display:inline-block;background:#ffe8cc;color:#E6A23C;border-radius:6px;padding:2px 8px;font-size:12px}
        .kv{display:flex;gap:6px;align-items:center;margin-top:6px;color:var(--text)}
        .btn-link{border:none;background:transparent;color:var(--primary)}
        .footer{position:fixed;left:0;right:0;bottom:0;height:60px;padding-bottom:env(safe-area-inset-bottom);background:var(--card);border-top:1px solid var(--border);display:flex;box-shadow:0 -2px 8px rgba(0,0,0,.04);max-width:480px;margin:0 auto;z-index:100}
        .tab{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;color:var(--subtext);font-size:13px;text-decoration:none}
        .tab.active{color:var(--primary);font-weight:600}
        .tab .dot{width:6px;height:6px;border-radius:50%;background:transparent;margin-top:4px}
        .tab.active .dot{background:var(--primary)}
        /* 抽屉复用 */
        .drawer-mask{position:fixed;inset:0;background:rgba(0,0,0,.35);opacity:0;pointer-events:none;transition:opacity .25s ease;z-index:999}
        .drawer-mask.open{opacity:1;pointer-events:auto}
        .drawer{position:fixed;top:0;right:0;height:100vh;width:86vw;max-width:420px;background:var(--card);border-left:1px solid var(--border);box-shadow:-12px 0 24px rgba(0,0,0,.12);transform:translateX(100%);transition:transform .25s ease;z-index:1000;display:flex;flex-direction:column}
        .drawer.open{transform:translateX(0)}
        .drawer-header{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;border-bottom:1px solid var(--border);font-weight:600}
        .drawer-body{padding:0 14px 14px;color:var(--subtext);font-size:14px;overflow:auto}
        .drawer-row{display:flex;justify-content:space-between;padding:12px 0;border-bottom:1px solid var(--border);color:var(--text)}
        .drawer-row:last-child{border-bottom:none}
        .drawer-foot{display:flex;gap:10px;padding:12px;background:var(--bg);border-top:1px solid var(--border)}
        .btn{height:40px;border-radius:10px;border:1px solid var(--border);background:#fff;color:var(--text);flex:1}
        .btn-danger{background:#F56C6C;color:#fff;border:none}
        
        /* 详情按钮样式 */
        .row-actions{ margin-top:10px; text-align:right; }
        .btn-detail{ background:var(--primary); color:white; border:none; padding:6px 12px; border-radius:4px; font-size:12px; cursor:pointer; }
        .btn-detail:hover{ background:#66b1ff; }
        
        /* 修改密码模态框样式 */
        .password-modal{ position:fixed; inset:0; background:rgba(0,0,0,.5); display:none; align-items:center; justify-content:center; z-index:2000; }
        .password-modal.open{ display:flex; }
        .password-dialog{ background:var(--card); border-radius:12px; padding:20px; width:90%; max-width:400px; box-shadow:0 8px 32px rgba(0,0,0,.2); }
        .password-header{ display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; }
        .password-title{ font-size:18px; font-weight:600; color:var(--text); }
        .password-close{ background:none; border:none; font-size:24px; color:var(--subtext); cursor:pointer; }
        .password-form{ display:block; }
        .form-group{ margin-bottom:16px; }
        .form-label{ display:block; margin-bottom:6px; color:var(--text); font-size:14px; font-weight:500; }
        .form-input{ width:100%; height:40px; border:1px solid var(--border); border-radius:8px; padding:0 12px; font-size:14px; color:var(--text); background:var(--card); }
        .form-input:focus{ outline:none; border-color:var(--primary); box-shadow:0 0 0 2px rgba(64,158,255,.2); }
        .password-actions{ display:flex; gap:12px; margin-top:20px; }
        .btn-submit{ flex:1; height:40px; background:var(--primary); color:#fff; border:none; border-radius:8px; font-size:14px; cursor:pointer; }
        .btn-cancel{ flex:1; height:40px; background:var(--bg); color:var(--text); border:1px solid var(--border); border-radius:8px; font-size:14px; cursor:pointer; }
        .error-message{ color:var(--danger); font-size:12px; margin-top:4px; }
        
        /* 项目选择列表样式 */
        .project-list-item{
            padding:14px 16px; background:var(--bg); border-radius:10px; border:1px solid var(--border);
            margin-bottom:10px; cursor:pointer; transition:background .2s, border-color .2s;
        }
        .project-list-item:hover{ background:rgba(64,158,255,.08); border-color:var(--primary); }
        .project-list-item.selected{ background:rgba(64,158,255,.12); border-color:var(--primary); }
        .project-list-name{ font-size:15px; font-weight:600; color:var(--text); margin-bottom:4px; }
        .project-list-short{ font-size:12px; color:var(--subtext); }
        
        /* 项目选择弹窗样式 */
        .project-modal{ position:fixed; inset:0; background:rgba(0,0,0,.45); opacity:0; pointer-events:none; transition:opacity .25s ease; z-index:2000; }
        .project-modal.open{ opacity:1; pointer-events:auto; }
        .project-dialog{ position:fixed; top:50%; left:50%; transform:translate(-50%, -48%) scale(.92); background:var(--card); border-radius:16px; width:88vw; max-width:420px; box-shadow:0 18px 40px rgba(31,45,61,.28); transition:transform .25s ease; }
        .project-modal.open .project-dialog{ transform:translate(-50%, -50%) scale(1); }
        .project-header{ padding:20px 20px 0; display:flex; align-items:center; justify-content:space-between; }
        .project-title{ font-size:18px; font-weight:700; color:var(--text); }
        .project-close{ width:28px; height:28px; border:none; background:none; font-size:20px; color:var(--subtext); cursor:pointer; }
        .project-body{ padding:18px 20px 12px; max-height:400px; overflow-y:auto; }
        .project-footer{ padding:0 20px 20px; display:flex; gap:12px; }
        .project-btn{ flex:1; height:42px; border-radius:12px; border:1px solid var(--border); background:var(--bg); color:var(--text); font-size:15px; cursor:pointer; }
    </style>
</head>
<body>
    <div class="page">
        <!-- 白色吸顶框包含用户信息 -->
        <div class="header-box">
            <button class="project-select-btn" id="projectSelectBtn" type="button" title="选择项目">
                <span id="projectSelectText">物测</span>
            </button>
            <button class="user" id="userBtn" type="button" title="查看个人信息">
                <span class="user-avatar" id="userAvatar">U</span>
                <span id="userName">用户</span>
            </button>
        </div>

        <!-- 筛选区 -->
        <div class="filters">
            <!-- 第一行：时间周期 -->
            <div class="filter-row">
                <select class="filter-select" id="timeSelect">
                    <option value="24h" selected>24小时</option>
                    <option value="7d">7天</option>
                    <option value="30d">30天</option>
                </select>
            </div>
            
            <!-- 第二行：告警等级、处理状态 -->
            <div class="filter-row">
                <select class="filter-select" id="levelSelect">
                    <option value="">全部等级</option>
                    <option value="critical">预警</option>
                    <option value="critical">普通</option>
                    <option value="warning">重要</option>
                    <option value="info">紧急</option>
                </select>
                <select class="filter-select" id="statusSelect">
                    <option value="">处理状态</option>
                    <option value="pending">未处理</option>
                    <option value="resolved">已处理</option>
                </select>
            </div>
            
            <!-- 第三行：搜索和重置按钮 -->
            <div class="button-row">
                <button class="btn-primary" id="searchBtn">搜索</button>
                <button class="btn-plain" id="resetBtn">重置</button>
            </div>
        </div>

        <!-- Tab容器 -->
        <div class="tab-container">
            <div class="tab-header">
                <button class="tab-btn active" data-tab="detail">告警详情</button>
                <button class="tab-btn" data-tab="report">告警报表</button>
            </div>
            
            <!-- 告警详情Tab -->
            <div class="tab-content active" id="detail-tab">
        <div class="list">
            <div class="row">
                <div class="meta">
                    <span>所属网点：物联网内部测试系统</span>
                    <span>告警级别：预警</span>
                    <span>处理状态：未处理</span>
                </div>
                <div class="kv"><span class="tag">水位0.29m>阈值10.00m</span><span class="tag">各类开关量1.00 =阈值1.00</span></div>
                <div class="kv"><span class="tag">液压-0.38MPa>阈值0.80MPa</span></div>
                <div class="kv" style="margin-top:10px;color:var(--subtext)">告警时间：2025-10-22 10:53:13</div>
                <div class="row-actions">
                    <button class="btn-detail" onclick="viewAlarmDetail(1)">详情</button>
                </div>
            </div>
            <div class="row">
                <div class="meta">
                    <span>所属网点：物联网内部测试系统</span>
                    <span>告警级别：预警</span>
                    <span>处理状态：未处理</span>
                </div>
                <div class="kv"><span class="tag">水位0.29m>阈值10.00m</span><span class="tag">液压-0.38MPa>阈值0.80MPa</span></div>
                <div class="kv"><span class="tag">各类开关量1.00 =阈值1.00</span></div>
                <div class="kv" style="margin-top:10px;color:var(--subtext)">告警时间：2025-10-22 10:43:09</div>
                <div class="row-actions">
                    <button class="btn-detail" onclick="viewAlarmDetail(2)">详情</button>
                </div>
            </div>
                </div>
            </div>
            
            <!-- 告警报表Tab -->
            <div class="tab-content" id="report-tab">
                <!-- 统计数据 -->
                <div class="report-stats">
                    <div class="stat-card">
                        <div class="stat-value" id="totalAlarms">0</div>
                        <div class="stat-label">告警总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="pendingAlarms">0</div>
                        <div class="stat-label">未处理</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="resolvedAlarms">0</div>
                        <div class="stat-label">已处理</div>
                    </div>
                </div>
                
                <!-- 等级统计 -->
                <div class="level-stats">
                    <div class="level-card">
                        <div class="level-value" id="warningCount">0</div>
                        <div class="level-label">预警</div>
                    </div>
                    <div class="level-card warning">
                        <div class="level-value warning" id="normalCount">0</div>
                        <div class="level-label">普通</div>
                    </div>
                    <div class="level-card danger">
                        <div class="level-value danger" id="importantCount">0</div>
                        <div class="level-label">重要</div>
                    </div>
                    <div class="level-card info">
                        <div class="level-value info" id="urgentCount">0</div>
                        <div class="level-label">紧急</div>
                    </div>
                </div>
                
                <!-- 图表容器 -->
                <div class="chart-container">
                    <canvas id="alarmChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 抽屉与遮罩 -->
    <div class="drawer-mask" id="drawerMask"></div>
    <aside class="drawer" id="userDrawer" aria-label="个人信息">
        <div class="drawer-header"><span>个人信息</span></div>
        <div class="drawer-body">
            <div class="drawer-row" style="padding:20px 0 12px; text-align:center;">
                <button id="userInfoBtn" class="btn btn-primary" style="width:100%; height:48px; font-size:16px;">查看个人信息</button>
            </div>
            <div class="drawer-row" style="border-bottom:none; padding:12px 0 20px; text-align:center;">
                <button id="controlPanelBtn" class="btn" style="width:100%; height:48px; font-size:16px; background:var(--ok); color:#fff; border-color:var(--ok);">操作面板展示</button>
            </div>
        </div>
        <div class="drawer-foot">
            <button id="changePasswordBtn" class="btn" style="flex:1; background:var(--primary); color:#fff; border:none;">修改密码</button>
            <button id="logoutBtn" class="btn btn-danger">退出登录</button>
            <button id="closePanel" class="btn">关闭</button>
        </div>
    </aside>

    <!-- 项目选择弹窗 -->
    <div class="project-modal" id="projectSelectModal">
        <div class="project-dialog">
            <div class="project-header">
                <div class="project-title">选择项目</div>
                <button class="project-close" data-close="projectSelectModal">×</button>
            </div>
            <div class="project-body">
                <div id="projectSelectList">
                    <!-- 动态生成的项目列表 -->
                </div>
            </div>
            <div class="project-footer">
                <button class="project-btn" data-close="projectSelectModal">取消</button>
            </div>
        </div>
    </div>

    <!-- 修改密码模态框 -->
    <div class="password-modal" id="passwordModal">
        <div class="password-dialog">
            <div class="password-header">
                <span class="password-title">修改密码</span>
                <button class="password-close" id="passwordClose">&times;</button>
            </div>
            <form class="password-form" id="passwordForm">
                <div class="form-group">
                    <label class="form-label" for="currentPassword">当前密码</label>
                    <input type="password" class="form-input" id="currentPassword" placeholder="请输入当前密码" required>
                    <div class="error-message" id="currentPasswordError"></div>
                </div>
                <div class="form-group">
                    <label class="form-label" for="newPassword">新密码</label>
                    <input type="password" class="form-input" id="newPassword" placeholder="请输入新密码" required>
                    <div class="error-message" id="newPasswordError"></div>
                </div>
                <div class="form-group">
                    <label class="form-label" for="confirmPassword">确认新密码</label>
                    <input type="password" class="form-input" id="confirmPassword" placeholder="请再次输入新密码" required>
                    <div class="error-message" id="confirmPasswordError"></div>
                </div>
                <div class="password-actions">
                    <button type="button" class="btn-cancel" id="passwordCancel">取消</button>
                    <button type="submit" class="btn-submit">确认修改</button>
                </div>
            </form>
        </div>
    </div>

    <nav class="footer">
        <a class="tab" href="system-overview.html">
            <span>首页</span>
            <span class="dot"></span>
        </a>
        <a class="tab" href="device-list.html">
            <span>设备</span>
            <span class="dot"></span>
        </a>
        <a class="tab active" href="alarm-list.html" aria-current="page">
            <span>告警</span>
            <span class="dot"></span>
        </a>
    </nav>

    <script>
        (function(){
            const u = JSON.parse(localStorage.getItem('currentUser')||'{}');
            document.getElementById('userName').textContent = u.name || '用户';
            document.getElementById('userAvatar').textContent = (u.name||'U').slice(0,1);
        })();
        
        // 项目选择功能
        (function(){
            const STORAGE_KEY = 'selectedProject';
            const projectSelectBtn = document.getElementById('projectSelectBtn');
            const projectSelectText = document.getElementById('projectSelectText');
            const projectSelectModal = document.getElementById('projectSelectModal');
            const projectSelectList = document.getElementById('projectSelectList');
            
            // 项目数据（名称和简称，简称应为四字或五字，如果没有简称则显示全称）
            const projects = [
                { id: '1', name: '物联网内部测试系统', short: '物联网测试系统' },
                { id: '2', name: '智慧园区示范点', short: '智慧园区示范' },
                { id: '3', name: '城市水务试点', short: '城市水务试点' },
                { id: '4', name: '智能办公大楼物联网控制系统' } // 没有简称，将显示全称
            ];
            
            // 获取当前选中的项目
            function getSelectedProject(){
                const saved = localStorage.getItem(STORAGE_KEY);
                if(saved){
                    try{
                        const selected = JSON.parse(saved);
                        return projects.find(p => p.id === selected.id) || projects[0];
                    }catch(e){
                        console.error('解析项目数据失败', e);
                    }
                }
                return projects[0]; // 默认第一个
            }
            
            // 保存选中的项目
            function saveSelectedProject(project){
                localStorage.setItem(STORAGE_KEY, JSON.stringify({ id: project.id }));
            }
            
            // 更新显示文本
            function updateDisplayText(){
                const selected = getSelectedProject();
                // 如果有简称则显示简称，否则显示全称（即使显示不全也可以）
                projectSelectText.textContent = selected.short || selected.name;
            }
            
            // 渲染项目列表
            function renderProjectList(){
                const selected = getSelectedProject();
                projectSelectList.innerHTML = '';
                
                projects.forEach(project => {
                    const item = document.createElement('div');
                    item.className = 'project-list-item';
                    if(project.id === selected.id){
                        item.classList.add('selected');
                    }
                    
                    item.innerHTML = `
                        <div class="project-list-name">${project.name}</div>
                        <div class="project-list-short">${project.short ? `简称：${project.short}` : '（无简称，显示全称）'}</div>
                    `;
                    
                    item.addEventListener('click', () => {
                        saveSelectedProject(project);
                        updateDisplayText();
                        renderProjectList();
                        closeProjectModal();
                        // 这里可以添加项目切换后的其他逻辑
                    });
                    
                    projectSelectList.appendChild(item);
                });
            }
            
            // 打开/关闭弹窗
            function openProjectModal(){
                renderProjectList();
                projectSelectModal.classList.add('open');
            }
            
            function closeProjectModal(){
                projectSelectModal.classList.remove('open');
            }
            
            // 事件监听
            projectSelectBtn.addEventListener('click', openProjectModal);
            
            // 关闭弹窗按钮
            document.querySelectorAll('[data-close="projectSelectModal"]').forEach(btn => {
                btn.addEventListener('click', closeProjectModal);
            });
            
            // 点击遮罩关闭弹窗
            projectSelectModal.addEventListener('click', (e) => {
                if(e.target === projectSelectModal) closeProjectModal();
            });
            
            // 初始化显示
            updateDisplayText();
        })();
        
        const drawer=document.getElementById('userDrawer');
        const mask=document.getElementById('drawerMask');
        function openDrawer(){drawer.classList.add('open');mask.classList.add('open')}
        function closeDrawer(){drawer.classList.remove('open');mask.classList.remove('open')}
        document.getElementById('userBtn').addEventListener('click',openDrawer);
        document.getElementById('closePanel').addEventListener('click',closeDrawer);
        mask.addEventListener('click',closeDrawer);
        document.getElementById('userInfoBtn').addEventListener('click',()=>{closeDrawer();location.href='user-info.html'});
        document.getElementById('controlPanelBtn').addEventListener('click',()=>{closeDrawer();location.href='control-panel-demo.html'});
        document.getElementById('logoutBtn').addEventListener('click',()=>{localStorage.removeItem('currentUser');location.href='mobile-login-demo.html'})
        document.addEventListener('keydown',e=>{if(e.key==='Escape')closeDrawer()});
        
        // 初始化图表
        let alarmChart = null;
        initChart();
        
        // 页面加载时初始化报表数据
        updateReportData();
        
        // Tab切换功能
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const tabId = this.getAttribute('data-tab');
                
                // 移除所有active类
                document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                
                // 添加active类到当前tab
                this.classList.add('active');
                document.getElementById(tabId + '-tab').classList.add('active');
                
                // 如果切换到报表tab，更新数据
                if (tabId === 'report') {
                    updateReportData();
                }
            });
        });
        
        // 筛选功能
        document.getElementById('searchBtn').addEventListener('click', function() {
            updateReportData();
        });
        
        document.getElementById('resetBtn').addEventListener('click', function() {
            document.getElementById('timeSelect').value = '24h';
            document.getElementById('levelSelect').value = '';
            document.getElementById('statusSelect').value = '';
            updateReportData();
        });
        
        // 初始化图表
        function initChart() {
            const ctx = document.getElementById('alarmChart').getContext('2d');
            alarmChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '告警数量',
                        data: [],
                        borderColor: '#409EFF',
                        backgroundColor: 'rgba(64, 158, 255, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            display: true,
                            title: {
                                display: true,
                                text: '告警数量'
                            },
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        // 更新报表数据
        function updateReportData() {
            const time = document.getElementById('timeSelect').value;
            const level = document.getElementById('levelSelect').value;
            const status = document.getElementById('statusSelect').value;
            
            // 模拟数据生成
            const data = generateAlarmData(time, level, status);
            
            // 更新统计数据
            document.getElementById('totalAlarms').textContent = data.total;
            document.getElementById('pendingAlarms').textContent = data.pending;
            document.getElementById('resolvedAlarms').textContent = data.resolved;
            
            // 更新等级统计
            document.getElementById('warningCount').textContent = data.levelStats.warning;
            document.getElementById('normalCount').textContent = data.levelStats.normal;
            document.getElementById('importantCount').textContent = data.levelStats.important;
            document.getElementById('urgentCount').textContent = data.levelStats.urgent;
            
            // 更新图表
            alarmChart.data.labels = data.labels;
            alarmChart.data.datasets[0].data = data.chartData;
            alarmChart.update();
        }
        
        // 生成告警数据
        function generateAlarmData(timePeriod, level, status) {
            const now = new Date();
            let labels = [];
            let chartData = [];
            let total = 0;
            let pending = 0;
            let resolved = 0;
            
            // 等级统计
            let levelStats = {
                warning: 0,    // 预警
                normal: 0,     // 普通
                important: 0,  // 重要
                urgent: 0      // 紧急
            };
            
            // 生成等级分布权重
            const levelWeights = {
                warning: 0.4,    // 40% 预警
                normal: 0.3,     // 30% 普通
                important: 0.2,  // 20% 重要
                urgent: 0.1      // 10% 紧急
            };
            
            if (timePeriod === '24h') {
                // 24小时数据 - 每小时
                for (let i = 23; i >= 0; i--) {
                    const time = new Date(now.getTime() - i * 60 * 60 * 1000);
                    labels.push(time.getHours() + ':00');
                    
                    const count = Math.floor(Math.random() * 10) + 1;
                    chartData.push(count);
                    total += count;
                    
                    // 按等级分配告警数量
                    const levelDistribution = distributeByLevel(count, levelWeights, level);
                    levelStats.warning += levelDistribution.warning;
                    levelStats.normal += levelDistribution.normal;
                    levelStats.important += levelDistribution.important;
                    levelStats.urgent += levelDistribution.urgent;
                    
                    if (Math.random() > 0.3) pending += count;
                    else resolved += count;
                }
            } else if (timePeriod === '7d') {
                // 7天数据 - 每天
                for (let i = 6; i >= 0; i--) {
                    const time = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
                    labels.push((time.getMonth() + 1) + '/' + time.getDate());
                    
                    const count = Math.floor(Math.random() * 50) + 10;
                    chartData.push(count);
                    total += count;
                    
                    // 按等级分配告警数量
                    const levelDistribution = distributeByLevel(count, levelWeights, level);
                    levelStats.warning += levelDistribution.warning;
                    levelStats.normal += levelDistribution.normal;
                    levelStats.important += levelDistribution.important;
                    levelStats.urgent += levelDistribution.urgent;
                    
                    if (Math.random() > 0.4) pending += count;
                    else resolved += count;
                }
            } else if (timePeriod === '30d') {
                // 30天数据 - 每天
                for (let i = 29; i >= 0; i--) {
                    const time = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
                    labels.push((time.getMonth() + 1) + '/' + time.getDate());
                    
                    const count = Math.floor(Math.random() * 30) + 5;
                    chartData.push(count);
                    total += count;
                    
                    // 按等级分配告警数量
                    const levelDistribution = distributeByLevel(count, levelWeights, level);
                    levelStats.warning += levelDistribution.warning;
                    levelStats.normal += levelDistribution.normal;
                    levelStats.important += levelDistribution.important;
                    levelStats.urgent += levelDistribution.urgent;
                    
                    if (Math.random() > 0.5) pending += count;
                    else resolved += count;
                }
            }
            
            return {
                labels: labels,
                chartData: chartData,
                total: total,
                pending: pending,
                resolved: resolved,
                levelStats: levelStats
            };
        }
        
        // 按等级分配告警数量
        function distributeByLevel(totalCount, weights, selectedLevel) {
            let distribution = {
                warning: 0,
                normal: 0,
                important: 0,
                urgent: 0
            };
            
            // 如果选择了特定等级，只显示该等级的数据
            if (selectedLevel) {
                const levelMap = {
                    'critical': 'warning',  // 预警
                    'warning': 'important', // 重要
                    'info': 'urgent'        // 紧急
                };
                const targetLevel = levelMap[selectedLevel] || 'normal';
                distribution[targetLevel] = totalCount;
                return distribution;
            }
            
            // 按权重分配
            let remaining = totalCount;
            const levels = ['warning', 'normal', 'important', 'urgent'];
            
            for (let i = 0; i < levels.length - 1; i++) {
                const level = levels[i];
                const count = Math.floor(totalCount * weights[level] + Math.random() * 2 - 1);
                distribution[level] = Math.max(0, Math.min(count, remaining));
                remaining -= distribution[level];
            }
            
            // 剩余数量分配给最后一个等级
            distribution.urgent = Math.max(0, remaining);
            
            return distribution;
        }
        
        // 详情查看功能 - 跳转到详情页面
        window.viewAlarmDetail = function(alarmId) {
            // 跳转到告警详情页面，传递告警ID参数
            window.location.href = `alarm-detail.html?id=${alarmId}`;
        };
        
        // 修改密码功能
        const passwordModal = document.getElementById('passwordModal');
        const passwordForm = document.getElementById('passwordForm');
        
        function openPasswordModal() {
            passwordModal.classList.add('open');
            // 关闭个人信息抽屉
            closeDrawer();
        }
        
        function closePasswordModal() {
            passwordModal.classList.remove('open');
            // 清空表单和错误信息
            passwordForm.reset();
            clearPasswordErrors();
        }
        
        function clearPasswordErrors() {
            document.getElementById('currentPasswordError').textContent = '';
            document.getElementById('newPasswordError').textContent = '';
            document.getElementById('confirmPasswordError').textContent = '';
        }
        
        function showPasswordError(fieldId, message) {
            document.getElementById(fieldId + 'Error').textContent = message;
        }
        
        function validatePassword() {
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            clearPasswordErrors();
            let isValid = true;
            
            // 验证当前密码（这里简化处理，实际应该与服务器验证）
            if (!currentPassword) {
                showPasswordError('currentPassword', '请输入当前密码');
                isValid = false;
            }
            
            // 验证新密码
            if (!newPassword) {
                showPasswordError('newPassword', '请输入新密码');
                isValid = false;
            } else if (newPassword.length < 6) {
                showPasswordError('newPassword', '密码长度至少6位');
                isValid = false;
            }
            
            // 验证确认密码
            if (!confirmPassword) {
                showPasswordError('confirmPassword', '请确认新密码');
                isValid = false;
            } else if (newPassword !== confirmPassword) {
                showPasswordError('confirmPassword', '两次输入的密码不一致');
                isValid = false;
            }
            
            return isValid;
        }
        
        // 事件监听
        document.getElementById('changePasswordBtn').addEventListener('click', openPasswordModal);
        document.getElementById('passwordClose').addEventListener('click', closePasswordModal);
        document.getElementById('passwordCancel').addEventListener('click', closePasswordModal);
        
        // 点击模态框背景关闭
        passwordModal.addEventListener('click', (e) => {
            if (e.target === passwordModal) {
                closePasswordModal();
            }
        });
        
        // 表单提交
        passwordForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            if (validatePassword()) {
                // 这里应该调用API修改密码
                alert('密码修改成功！');
                closePasswordModal();
            }
        });
        
        // Esc键关闭密码模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && passwordModal.classList.contains('open')) {
                closePasswordModal();
            }
        });
    </script>
</body>
</html>

